<template>
    <div>
        <el-dialog :title="flag ? '批量下发指令' : '下发指令'" :visible.sync="dialogVisible" width="450px" :before-close="closeDialog"
            :close-on-click-modal="false">
            <el-form :model="addForm" :rules="rules" ref="refForm" label-width="95px">
                <el-form-item size="small" label="服务标识" prop="serviceType">
                    <el-select v-model="addForm.serviceType" filterable placeholder="请选择" style="width: 320px"
                        @change='onChange'>
                        <el-option v-for="(item, i) in CommandInfo" :key="i" :label="item.serviceName"
                            :value="item.serviceType">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item size="small" label="服务值" prop="serviceValue" v-if="inputType != ''">
                    <el-select v-model="addForm.serviceValue" filterable placeholder="请选择" style="width: 320px"
                        v-if="inputType == 2">
                        <el-option v-for="(item, i) in dataDefinition2" :key="i" :label="item.key" :value="item.value">
                        </el-option>
                    </el-select>
                    <el-input maxlength="5" clearable v-model.trim="addForm.serviceValue" v-if="inputType == 1"
                        :placeholder="placeholderStr"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeDialog" class="cancel-button">取 消</el-button>
                <el-button size="small"  @click="submit" v-preventReClick="1000" class="confirm-button">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { reqCommand, reqBatchCommand, reqCommandServicePage } from "@api/api.js";
import { mapState } from "vuex";

export default {
    props: ['deviceInfo', 'idList', 'CommandInfo'],
    data() {
        var checkPass = (rule, value, callback) => {
            // console.log(this.inputType);
            // console.log(typeof Number(value));
            // console.log(typeof Number(this.num1));
              // 首先检查value是否是一个有效的小数
              const reg = /^\d+(\.\d+)?$/;
            if (!reg.test(value)) {
                return callback(new Error("请输入正确的取值范围"));
            }
            if(this.inputType==1 && (Number(value)>Number(this.num2) || Number(value)<Number(this.num1))){
                callback(new Error("请输入正确的取值范围"));
            }else{
                callback();
            }
    };
        return {
            dialogVisible: false,
            addForm: {
                serviceType: "",
                serviceValue: "",
            },
            rules: {
                serviceType: [
                    { required: true, message: "请选择服务标识", trigger: "change" },
                ],
                serviceValue: [{ required: true, message: "请选择服务值", trigger: "change" }, {
            validator: checkPass,
            trigger: "change"
          },],
            },
            flag: false,
            inputType: '',
            dataDefinition2: [],
            num1: 1,
            num2: 100,
            placeholderStr: "",
            identifier: ""//标识符
        };
    },
    computed: {
        ...mapState(["user"]),
    },
    watch: {
        idList(val) {
            // console.log(val);
            this.flag = true;
        },
        // dialogVisible(e){
        //     if(e && this.CommandInfo.inputType==2){
        //         this.CommandInfo.dataDefinition=JSON.parse(this.CommandInfo.dataDefinition)
        //     }
        // },
    },
    mounted() { },
    methods: {
        onChange(e) {
            // console.log(e);
            this.addForm.serviceValue = ''
            this.CommandInfo.forEach(element => {
                if (element.serviceType == e) {
                    this.inputType = element.inputType
                    this.identifier = element.identifier
                    if (element.inputType == 1) {
                        this.num1 = element.dataDefinition.substring(0, element.dataDefinition.indexOf(','))
                        this.num2 = element.dataDefinition.substring(element.dataDefinition.indexOf(',') + 1)
                        this.placeholderStr = `请输入服务值（${this.num1}-${this.num2}）`
                        this.rules.serviceValue[0].message = '请输入服务值'
                    } else {
                        this.dataDefinition2 = JSON.parse(element.dataDefinition)
                        this.rules.serviceValue[0].message = '请选择服务值'
                    }
                }
            });
        },
        // 获取指令服务
        // async getCommandServicePage(deviceInfo){
        //     const res = await reqCommandServicePage(1,50,{
        //         productModel:deviceInfo.classMark,
        //         protocol:deviceInfo.protocol,
        //     });
        //         if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        //         console.log(res);
        // },

        submit(e) {
            // console.log(e);
            this.$refs.refForm.validate(async (valid) => {
                if (!valid) return;
                let { serviceType, serviceValue } = this.addForm;
                if (this.flag) {
                    // 批量下发
                    const res = await reqBatchCommand({
                        serviceType,
                        serviceValue,
                        idList: this.idList,
                        identifier: this.identifier,
                    });
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                    this.$modal.notifySuccess("批量下发指令成功！");
                    this.$parent.clearSelections();//清空复选框
                } else {
                    const res = await reqCommand({
                        serviceType,
                        serviceValue,
                        imei: this.deviceInfo.imei,
                        deviceId: this.deviceInfo.deviceId,
                        identifier: this.identifier,
                    });
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                    this.$modal.notifySuccess("下发指令成功！");
                    this.$parent.CommandPage();
                }
                this.closeDialog()
            });
        },
        // 点击关闭弹框
        closeDialog() {
            this.rules.serviceValue[0].message = '请选择服务值'
            this.$refs.refForm.resetFields();
            this.dialogVisible = false;
            this.inputType = ''
            this.addForm = {
                serviceType: "",
                serviceValue: "",
            }
        },
    },
};
</script>

<style lang="less" scoped>
// 下拉框加载开始
.div_box {
    height: 276px;
    position: absolute;
    top: -1px;
    left: -1px;
    width: 100%;
    z-index: 2016;
    // background: red;
    // opacity: 0.5;
}

::v-deep .el-loading-mask {
    border-radius: 4px;
}

// 下拉框加载结束
</style>